package com.desire;


import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author desire
 */
public class Publisher {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接
        ConnectionFactory factory = new ConnectionFactory();
        // 配置连接信息  类似于 MySQL连接信息
        // 设置用户名 密码
        factory.setUsername("admin");
        factory.setPassword("123");
        // 设置mq服务器地址 默认是 localhost
        factory.setHost("116.63.151.50");
        // 设置高级消息队列amqp 端口号
        factory.setPort(5672);
        // 设置虚拟主机，默认是 /
        factory.setVirtualHost("erp");

        // 获取连接
        Connection connection = factory.newConnection();
        // 在连接上创建信道
        Channel channel = connection.createChannel();
        // 声明一个交换器 类型为 direct
        String exchangeName = "erp_logs";
        /**
         * 直连交换机（Direct exchange）： 具有路由功能的交换机，绑定到此交换机的时候需要指定一个routing_key，交换机发送消息的时候需要routing_key，会将消息发送道对应的队列
         * */
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT);
        // 声明2个队列
        String queueOne = "commonlog";
        String queueTwo = "errorlog";
        channel.queueDeclare(queueOne, false, false, false, null);
        channel.queueDeclare(queueTwo, false, false, false, null);

        // 将队列与交换器绑定   队列1 绑定了三个路由键，则三个路由键都会发送到交换器上 消费者携带路由键进行指定消费
        channel.queueBind(queueOne, exchangeName, "debug");
        channel.queueBind(queueOne, exchangeName, "info");
        channel.queueBind(queueOne, exchangeName, "warn");

        channel.queueBind(queueTwo, exchangeName, "error");

        // 发送消息
        channel.basicPublish(exchangeName, "debug", null, "霸哥".getBytes(StandardCharsets.UTF_8));
        channel.basicPublish(exchangeName, "info", null, "因佛".getBytes(StandardCharsets.UTF_8));
        channel.basicPublish(exchangeName, "warn", null, "沃恩".getBytes(StandardCharsets.UTF_8));

        channel.basicPublish(exchangeName, "error", null, "额若".getBytes(StandardCharsets.UTF_8));

        // 不存在的路由键会发送到默认的路由键上
        channel.basicPublish(exchangeName, "abd", null, "abd".getBytes(StandardCharsets.UTF_8));


        System.out.println("发送消息成功");
        // 关闭信道
        channel.close();
        // 关闭连接
        connection.close();
    }
}
